package controller

import (
	"encoding/json"
	"ez/apps/erp/auto/controller"
	erp "ez/apps/erp/document"
	"ez/apps/erp/service"
	"ez/config/code"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type NeedController struct {
	controller.NeedAutoController
}

func init() {
	c := NeedController{}
	c.SetRouteParam("/erp", "/admin", "Need")
	ez.CreateApi(c.AdminGet(), c.GetAction)
	ez.CreateApi(c.AdminList(), c.ListAction)
	ez.CreateApi(c.AdminSave(), c.SaveAction).Add(20, "检查锁定状态", c.CheckLockAction)
	ez.CreateApi(c.AdminCopy(), c.CopyAction)
	ez.CreateApi(c.AdminUpdate(), c.UpdateAction).Add(20, "检查锁定状态", c.CheckLockAction)
	ez.CreateApi(c.AdminChoice(), c.ChoiceAction)
	ez.CreateApi(c.AdminDelete(), c.DeleteAction).Add(20, "检查锁定状态", c.CheckLockAction)
	ez.CreateApi(c.AdminUnDelete(), c.UnDeleteAction).Add(20, "检查锁定状态", c.CheckLockAction)
	ez.CreateApi(c.AdminDestroy(), c.DestroyAction).Add(20, "检查锁定状态", c.CheckLockAction)
	ez.CreateApi(c.AdminUpdateMany(), c.UpdateManyAction)
	ez.CreateApi(c.AdminDeleteMany(), c.DeleteManyAction)
	ez.CreateApi(c.AdminDestroyMany(), c.DestroyManyAction)
	ez.CreateApi(c.AdminApi("/Need/approval_start"), c.ApprovalStartAction)
	ez.CreateApi(c.AdminApi("/Need/approval_submit"), c.ApprovalSubmitAction)
	ez.CreateApi(c.AdminApi("/Need/approval_auth"), c.ApprovalAuthAction)
	ez.CreateApi(c.AdminApi("/Need/fast_inquiry"), c.FastInquiryAction)
	ez.CreateApi(c.AdminApi("/Need/fast_inquiryFeedback"), c.FastInquiryFeedbackAction)
	ez.CreateApi(c.AdminApi("/Need/fast_buyOrder"), c.FastBuyOrderAction)
}

// func (c NeedController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c NeedController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c NeedController) ListAction(session *ez.Session) { /* 在这里面重构 */ }

func (c NeedController) CheckLockAction(session *ez.Session) {
	this := cc.New(session)
	id := session.Get("id").IsInt64()
	if id == 0 {
		return
	}
	crud := erp.NewNeedCrud(session)
	find, _ := crud.FindId(id)
	if find.Id == 0 {
		this.ReturnError(code.ErrorNotFound, "信息未找到", "")
		session.StopHandle()
	}
	if find.IsLock {
		this.ReturnError(code.Error, "已锁定", "")
		session.StopHandle()
	}
}

func (c NeedController) FastInquiryAction(session *ez.Session) {
	this := cc.New(session)

	need, e := erp.NewNeedCrud(session).FindId(this.Get("id").IsInt64())
	if this.Try(e) {
		return
	}
	need.LoadProduct()

	//创建询价单
	inquiry := new(erp.Inquiry)
	inquiry.Sn = ""
	inquiry.Title = need.Title + " #快速询价单"
	inquiry.GetFactory().SetArgus(session)
	inquiry.SetEvent(true)
	if this.Try(inquiry.Save()) {
		return
	}
	for _, product := range need.Product {
		product.GetFactory().SetArgus(session)
		inquiryProduct := new(erp.InquiryProduct)
		inquiryProduct.UnSerialize(product.Serialize())
		inquiryProduct.BelongToId = inquiry.Id
		inquiryProduct.Src = need.Id
		inquiryProduct.SrcSN = need.Sn
		inquiryProduct.Id = 0
		inquiryProduct.GetFactory().SetArgus(session)
		if this.Try(inquiryProduct.Save()) {
			return
		}
	}
	this.ReturnSuccess("快速创建成功", "")
}
func (c NeedController) FastInquiryFeedbackAction(session *ez.Session) {
	this := cc.New(session)

	need, e := erp.NewNeedCrud(session).FindId(this.Get("id").IsInt64())
	if this.Try(e) {
		return
	}
	need.LoadProduct()

	//创建询价单
	inquiryFeedback := new(erp.InquiryFeedback)
	inquiryFeedback.Sn = ""
	inquiryFeedback.Title = need.Title + " #快速报价单"
	inquiryFeedback.GetFactory().SetArgus(session)
	inquiryFeedback.SetEvent(true)
	if this.Try(inquiryFeedback.Save()) {
		return
	}
	for _, product := range need.Product {
		product.GetFactory().SetArgus(session)
		inquiryProduct := new(erp.InquiryFeedbackProduct)
		inquiryProduct.UnSerialize(product.Serialize())
		inquiryProduct.BelongToId = inquiryFeedback.Id
		inquiryProduct.Src = need.Id
		inquiryProduct.SrcSN = need.Sn
		inquiryProduct.Id = 0
		inquiryProduct.GetFactory().SetArgus(session)
		if this.Try(inquiryProduct.Save()) {
			return
		}
	}
	this.ReturnSuccess("快速创建成功", "")
}
func (c NeedController) FastBuyOrderAction(session *ez.Session) {
	this := cc.New(session)

	need, e := erp.NewNeedCrud(session).FindId(this.Get("id").IsInt64())
	if this.Try(e) {
		return
	}
	need.LoadProduct()

	//创建询价单
	buyOrder := new(erp.BuyOrder)
	buyOrder.Sn = ""
	buyOrder.Title = need.Title + " #快速采购订单"
	buyOrder.GetFactory().SetArgus(session)
	buyOrder.SetEvent(true)
	if this.Try(buyOrder.Save()) {
		return
	}
	for _, product := range need.Product {
		product.GetFactory().SetArgus(session)
		buyOrderProduct := new(erp.BuyOrderProduct)
		buyOrderProduct.UnSerialize(product.Serialize())
		buyOrderProduct.BelongToId = buyOrder.Id
		buyOrderProduct.Src = need.Id
		buyOrderProduct.SrcSN = need.Sn
		buyOrderProduct.Id = 0
		buyOrderProduct.GetFactory().SetArgus(session)
		if this.Try(buyOrderProduct.Save()) {
			return
		}
	}
	this.ReturnSuccess("快速创建成功", "")
}

func (c NeedController) ApprovalAuthAction(session *ez.Session) {
	this := cc.New(session)
	id := this.Get("id").IsInt64()
	//auth := ss.M{}
	need, err := erp.NewNeedCrud(session).FindId(id)
	if this.Try(err) {
		return
	}
	//flows := service.GetFlowById(need.Flow)
	var authModel struct {
		Auth struct {
			User []struct {
				Id   int64  `json:"id" bson:"id"`
				Name string `json:"name" bson:"name"`
			} `json:"user"`
			Department []struct {
				Id   int64  `json:"id" bson:"id"`
				Name string `json:"name" bson:"name"`
			} `json:"department"`
		} `json:"auth"`
	}
	content, err := json.Marshal(need.FlowCur)
	if this.Try(err) {
		return
	}
	err = json.Unmarshal(content, &authModel)
	if this.Try(err) {
		return
	}
	//检查用户是否具有权限
	uid := this.GetUserId()
	emp, err := erp.NewEmpCrud(session).FindId(uid)

	userAccess := false
	departmentAccess := false
	for _, u := range authModel.Auth.User {
		if u.Id == uid {
			userAccess = true
		}
	}
	for _, dept := range authModel.Auth.Department {
		if dept.Id == emp.DepartmentId {
			departmentAccess = true
		}
	}
	editAccess := false
	if need.CreateEmpId == uid {
		editAccess = true
	}
	if need.FormEmpId == uid {
		editAccess = true
	}

	this.ReturnSuccess("OK", ss.M{
		"userAccess":       userAccess,
		"departmentAccess": departmentAccess,
		"editAccess":       editAccess,
		"isSuperAdmin":     uid == 1,
	})
}
func (c NeedController) ApprovalStartAction(session *ez.Session) {
	this := cc.New(session)
	id := this.Get("id").IsInt64()
	flowId := this.Get("flowId").IsInt64()
	need, err := erp.NewNeedCrud(session).FindId(id)
	if this.Try(err) {
		return
	}
	flows := service.GetFlowById(flowId)
	//need.Flows = make([]ss.M, 0)//这里要根据需求切换，如果需要在切换的时候清空就重新启用本行
	need.Flow = flowId
	if len(flows) > 0 {
		need.FlowName = flows[0]["name"].(string)
		need.FlowCur = flows[0]
		need.IsLock = true
	}
	need.IsConfirm = false
	need.StatusId = service.MustHaveNeedStep(service.NeedStatus_Approval_Start).Id
	need.Save()
	this.ReturnSuccess("OK", need)
}
func (c NeedController) ApprovalSubmitAction(session *ez.Session) {
	this := cc.New(session)
	need := new(erp.Need)
	if this.Try(this.FillJson(&need)) {
		return
	}
	//默认数据处理
	if need.FlowCur == nil {
		this.ReturnError(code.Error, "系统错误：", "")
		return
	}

	orgNeed, e := erp.NewNeedCrud(session).FindId(need.Id)
	if this.Try(e) {
		return
	}
	if orgNeed.IsConfirm {
		this.ReturnError(code.Error, "审批已完成", "")
		return
	}
	if orgNeed.IsCancel {
		this.ReturnError(code.Error, "采购申请已取消", "")
		return
	}
	if orgNeed.IsClose { //todo 这里我认为关闭和取消是一个状态
		this.ReturnError(code.Error, "采购申请已关闭", "")
		return
	}
	finalState := need.FlowCur["finalState"].(string)
	switch finalState {
	case "通过":
	case "驳回":
	case "取消":
		//取消操作
		orgNeed.FlowName = "审批流程已取消"
		orgNeed.Flows = append([]ss.M{need.FlowCur}, orgNeed.Flows...)
		orgNeed.StatusId = service.MustHaveNeedStep(service.NeedStatus_Approval_Cancel).Id
		if this.Try(orgNeed.Save()) {
			return
		}
		this.ReturnSuccess("OK", orgNeed)
		return
	case "完成":
		//完结操作
		orgNeed.ConfirmAt = time.Now()
		orgNeed.IsConfirm = true
		orgNeed.StatusId = service.MustHaveNeedStep(service.NeedStatus_Approval_Confirm).Id
		orgNeed.FlowName = "审批流程通过 [ 结束 ]"
	default:
		need.FlowCur["finalState"] = "通过"
	}

	need.FlowCur["fillAt"] = time.Now()
	orgNeed.Flows = append([]ss.M{need.FlowCur}, orgNeed.Flows...)
	flows := service.GetFlowById(orgNeed.Flow)
	noNextFount := true
	for index, flow := range flows {
		if flow["key"] == need.FlowCur["flowTo"] {
			orgNeed.FlowCur = flow
			orgNeed.FlowIndex = int64(index)
			orgNeed.FlowName, _ = flow["name"].(string)
			noNextFount = false
		}
	}
	if noNextFount {
		//检查是否是最后一个工序，如果是，正常完结
		//如果不是默认进入下一个
		if orgNeed.FlowIndex == int64(len(flows)-1) {
			//是最后一个工序
			orgNeed.ConfirmAt = time.Now()
			orgNeed.IsConfirm = true
			orgNeed.FlowName = "审批流程通过 [ 结束 ]"
		} else {
			orgNeed.FlowIndex++
			orgNeed.FlowCur = flows[orgNeed.FlowIndex]
			orgNeed.FlowName, _ = flows[orgNeed.FlowIndex]["name"].(string)

		}

	}
	if lock, ok := orgNeed.FlowCur["lock"]; ok && lock.(bool) {
		orgNeed.IsLock = true
	} else {
		orgNeed.IsLock = false
	}
	if this.Try(orgNeed.Save()) {
		return
	}
	this.ReturnSuccess("OK", orgNeed)
}
